<?php

namespace App\Http\Controllers;

use App\Http\Traits\ApiReturn;
use Illuminate\Support\Facades\Cache;

class AuthController extends Controller
{
    use ApiReturn;

    /**
     * Get a JWT via given credentials.
     * 该方法用于生成token
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $captcha = request(['captchaKey','captchaCode']); //验证码
        if (!captcha_api_check($captcha['captchaCode'], $captcha['captchaKey'],'flat')){
            return $this->err('A0213','验证码不正确或已过期');
        }
        $credentials = request(['username', 'password']);
        //dd(Hash::make(123456));
        if (!$token = auth('api')->attempt($credentials)) {
            return $this->err(401, '账号或密码错误');
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     * 该方法通过token获取对应的用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $user = auth('api')->user();

        $rolePerm = Cache::get('user_role_perms_key_'.$user->id);
        if (empty($rolePerm)) {
            $roles = $user->roles()->pluck('code')->unique()->toArray();
            $perms = $user->roles()->with(['menus' => function ($q) {
                $q->where('visible', 1)->whereIn('type', ['BUTTON']);
            }])->get()->pluck('menus')->flatten()->unique()->pluck('perm')->unique()->toarray();
            $rolePerm = ['roles' => $roles, 'perms' => $perms];
            //缓存两个小时
            Cache::put('user_role_perms_key_'.$user->id, $rolePerm, now()->addMinutes(15));
        } else {
            //Log::info('有数据');
        }

        $perms1 = [
            "sys:menu:delete",
            "sys:dept:edit",
            "sys:dict_type:add",
            "sys:dict:edit",
            "sys:dict:delete",
            "sys:dict_type:edit",
            "sys:menu:add",
            "sys:user:add",
            "sys:role:edit",
            "sys:dept:delete",
            "sys:user:edit",
            "sys:user:delete",
            "sys:user:password:reset",
            "sys:dept:add",
            "sys:role:delete",
            "sys:dict_type:delete",
            "sys:menu:edit",
            "sys:dict:add",
            "sys:role:add",
            "sys:user:query",
            "sys:user:export",
        ];
        $data = [
            "userId" => $user->id,
            "nickname" => $user->nickname,
            "username" => $user->username,
            "avatar" => $user->avatar,
            "roles" => $rolePerm['roles'],
            "perms" => $rolePerm['perms']
        ];


        return $this->succ($data);
    }

    public function captcha(){
        $img = app('captcha')->create('flat', true);
        return $this->succ(['captchaKey'=>$img['key'],'captchaBase64'=>$img['img']]);
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->forgetCache();

        auth('api')->logout();

        return $this->succ('退出成功');
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param string $token
     * 该方法按照指定的格式返回输出信息
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        $data = [
            'accessToken' => $token,
            'tokenType' => 'Bearer',
            'refreshToken' => null,
            'expires' => auth('api')->factory()->getTTL() * 60
        ];
        $this->forgetCache();
        return $this->succ($data, '登录成功');
    }

    protected function forgetCache(){
        $user = auth('api')->user();
        Cache::forget('user_role_perms_key_'.$user->id);
        Cache::forget('user_menus_key_'.$user->id);
    }
}

